<!--<template>-->
<!--  <div class="dashboard-container">-->
<!--    &lt;!&ndash; 设备情况统计模块 &ndash;&gt;-->
<!--    <div class="device-stats-container">-->
<!--      <h3 class="stats-title">设备情况</h3>-->
<!--      <div class="stats-cards">-->
<!--        <div class="stat-card blue-card">-->
<!--          <div class="card-title">使用统计</div>-->
<!--          <div class="card-items">-->
<!--            <div class="card-item">-->
<!--              <span class="item-label">全部设备</span>-->
<!--              <span class="item-value">276台</span>-->
<!--            </div>-->
<!--            <div class="card-item">-->
<!--              <span class="item-label">在用设备</span>-->
<!--              <span class="item-value">260台</span>-->
<!--            </div>-->
<!--            <div class="card-item">-->
<!--              <span class="item-label">闲置设备</span>-->
<!--              <span class="item-value">10台</span>-->
<!--            </div>-->
<!--            <div class="card-item">-->
<!--              <span class="item-label">停用设备</span>-->
<!--              <span class="item-value">6台</span>-->
<!--            </div>-->
<!--          </div>-->
<!--        </div>-->
<!--        <div class="stat-card orange-card">-->
<!--          <div class="card-title">激活情况（在用设备）</div>-->
<!--          <div class="card-items">-->
<!--            <div class="card-item">-->
<!--              <span class="item-label">已激活设备</span>-->
<!--              <span class="item-value">212台</span>-->
<!--            </div>-->
<!--            <div class="card-item">-->
<!--              <span class="item-label">未激活设备</span>-->
<!--              <span class="item-value">48台</span>-->
<!--            </div>-->
<!--          </div>-->
<!--        </div>-->
<!--        <div class="stat-card red-card">-->
<!--          <div class="card-title">运行状态（已激活设备）</div>-->
<!--          <div class="card-items">-->
<!--            <div class="card-item">-->
<!--              <span class="item-label">正常设备</span>-->
<!--              <span class="item-value">208台</span>-->
<!--            </div>-->
<!--            <div class="card-item">-->
<!--              <span class="item-label">故障设备</span>-->
<!--              <span class="item-value">4台</span>-->
<!--            </div>-->
<!--          </div>-->
<!--        </div>-->
<!--      </div>-->
<!--    </div>-->

<!--    &lt;!&ndash; 待办事项模块 &ndash;&gt;-->
<!--    <div class="todo-container">-->
<!--      <h3 class="todo-title">待办事项</h3>-->
<!--      <div class="todo-cards">-->
<!--        <div class="todo-card">-->
<!--          <span class="todo-label">待激活</span>-->
<!--          <span class="todo-count">2</span>-->
<!--        </div>-->
<!--        <div class="todo-card">-->
<!--          <span class="todo-label">待安装</span>-->
<!--          <span class="todo-count">0</span>-->
<!--        </div>-->
<!--        <div class="todo-card">-->
<!--          <span class="todo-label">型号补充</span>-->
<!--          <span class="todo-count">0</span>-->
<!--        </div>-->
<!--        <div class="todo-card">-->
<!--          <span class="todo-label">安装地点补充</span>-->
<!--          <span class="todo-count">1</span>-->
<!--        </div>-->
<!--      </div>-->
<!--    </div>-->

<!--    &lt;!&ndash; 在用设备排行柱状图模块 &ndash;&gt;-->
<!--    <div class="bar-chart-container">-->
<!--      <h3 class="chart-title">在用设备排行</h3>-->
<!--      <div class="chart-unit">单位：台</div>-->
<!--      <div ref="barChart" class="echarts-box" style="width: 100%; height: 400px;"></div>-->
<!--    </div>-->
<!--  </div>-->
<!--</template>-->

<!--<script setup>-->
<!--  import { ref, onMounted, onUnmounted } from 'vue'-->
<!--  import * as echarts from 'echarts'-->

<!--  // 设备情况和待办事项数据（静态演示，可替换为接口数据）-->
<!--  // 若需动态获取，引入 API 后在 onMounted 中请求-->

<!--  // 柱状图数据（静态演示）-->
<!--  const barData = {-->
<!--    xAxis: ['光刻机', '刻蚀机', '薄膜沉积设备', '离子注入机', '机械抛光', '清洗机', '氧化炉', '晶圆切割机', '晶元建博机', '测试机'],-->
<!--    yAxis: [84, 79, 60, 45, 40, 21, 18, 15, 11, 8]-->
<!--  }-->

<!--  // 图表容器引用-->
<!--  const barChart = ref(null)-->
<!--  let barChartInstance = null-->

<!--  onMounted(() => {-->
<!--    // 初始化柱状图-->
<!--    initBarChart()-->
<!--  })-->

<!--  onUnmounted(() => {-->
<!--    // 销毁图表实例-->
<!--    if (barChartInstance) {-->
<!--      barChartInstance.dispose()-->
<!--      barChartInstance = null-->
<!--    }-->
<!--  })-->

<!--  /**-->
<!--   * 初始化在用设备排行柱状图-->
<!--   */-->
<!--  const initBarChart = () => {-->
<!--    if (!barChart.value) return-->

<!--    // 初始化 ECharts 实例-->
<!--    barChartInstance = echarts.init(barChart.value)-->

<!--    // 配置项-->
<!--    const option = {-->
<!--      tooltip: {-->
<!--        trigger: 'axis',-->
<!--        axisPointer: { type: 'shadow' }-->
<!--      },-->
<!--      xAxis: {-->
<!--        type: 'category',-->
<!--        data: barData.xAxis,-->
<!--        axisLabel: {-->
<!--          color: '#666',-->
<!--          fontSize: 12-->
<!--        },-->
<!--        axisLine: {-->
<!--          lineStyle: { color: '#ccc' }-->
<!--        }-->
<!--      },-->
<!--      yAxis: {-->
<!--        type: 'value',-->
<!--        name: '数量（台）',-->
<!--        axisLabel: {-->
<!--          color: '#666',-->
<!--          fontSize: 12-->
<!--        },-->
<!--        axisLine: {-->
<!--          lineStyle: { color: '#ccc' }-->
<!--        },-->
<!--        splitLine: {-->
<!--          lineStyle: { color: '#f5f5f5' }-->
<!--        }-->
<!--      },-->
<!--      series: [-->
<!--        {-->
<!--          name: '在用设备数量',-->
<!--          type: 'bar',-->
<!--          data: barData.yAxis,-->
<!--          barWidth: '40%',-->
<!--          itemStyle: {-->
<!--            color: '#409eff',-->
<!--            borderRadius: [6, 6, 0, 0]-->
<!--          },-->
<!--          label: {-->
<!--            show: true,-->
<!--            position: 'top',-->
<!--            color: '#333'-->
<!--          }-->
<!--        }-->
<!--      ],-->
<!--      grid: {-->
<!--        left: '10%',-->
<!--        right: '10%',-->
<!--        bottom: '10%',-->
<!--        containLabel: true-->
<!--      }-->
<!--    }-->

<!--    // 设置配置项-->
<!--    barChartInstance.setOption(option)-->

<!--    // 监听窗口变化-->
<!--    window.addEventListener('resize', () => {-->
<!--      barChartInstance && barChartInstance.resize()-->
<!--    })-->
<!--  }-->
<!--</script>-->

<!--<style scoped>-->
<!--  .dashboard-container {-->
<!--    padding: 20px;-->
<!--  }-->

<!--  /* 设备情况统计模块样式 */-->
<!--  .device-stats-container {-->
<!--    margin-bottom: 30px;-->
<!--  }-->

<!--  .stats-title {-->
<!--    font-size: 18px;-->
<!--    font-weight: bold;-->
<!--    margin-bottom: 15px;-->
<!--  }-->

<!--  .stats-cards {-->
<!--    display: flex;-->
<!--    gap: 20px;-->
<!--    flex-wrap: wrap;-->
<!--  }-->

<!--  .stat-card {-->
<!--    flex: 1;-->
<!--    min-width: 280px;-->
<!--    border-radius: 8px;-->
<!--    padding: 15px;-->
<!--    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);-->
<!--  }-->

<!--  .blue-card {-->
<!--    background-color: #eaf5ff;-->
<!--  }-->

<!--  .orange-card {-->
<!--    background-color: #fff8e1;-->
<!--  }-->

<!--  .red-card {-->
<!--    background-color: #fff3f3;-->
<!--  }-->

<!--  .card-title {-->
<!--    font-size: 16px;-->
<!--    font-weight: bold;-->
<!--    margin-bottom: 10px;-->
<!--  }-->

<!--  .card-items {-->
<!--    display: flex;-->
<!--    flex-wrap: wrap;-->
<!--    gap: 15px;-->
<!--  }-->

<!--  .card-item {-->
<!--    display: flex;-->
<!--    flex-direction: column;-->
<!--  }-->

<!--  .item-label {-->
<!--    font-size: 12px;-->
<!--    color: #999;-->
<!--    margin-bottom: 4px;-->
<!--  }-->

<!--  .item-value {-->
<!--    font-size: 14px;-->
<!--    font-weight: 500;-->
<!--  }-->

<!--  /* 待办事项模块样式 */-->
<!--  .todo-container {-->
<!--    margin-top: 30px;-->
<!--    margin-bottom: 30px;-->
<!--  }-->

<!--  .todo-title {-->
<!--    font-size: 18px;-->
<!--    font-weight: bold;-->
<!--    margin-bottom: 15px;-->
<!--  }-->

<!--  .todo-cards {-->
<!--    display: flex;-->
<!--    gap: 20px;-->
<!--    flex-wrap: wrap;-->
<!--  }-->

<!--  .todo-card {-->
<!--    background-color: #f9f9f9;-->
<!--    border-radius: 8px;-->
<!--    padding: 15px 20px;-->
<!--    min-width: 180px;-->
<!--    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);-->
<!--    display: flex;-->
<!--    justify-content: space-between;-->
<!--    align-items: center;-->
<!--  }-->

<!--  .todo-label {-->
<!--    font-size: 14px;-->
<!--    color: #666;-->
<!--  }-->

<!--  .todo-count {-->
<!--    font-size: 16px;-->
<!--    font-weight: bold;-->
<!--    color: #ff9900;-->
<!--  }-->

<!--  /* 在用设备排行柱状图样式 */-->
<!--  .bar-chart-container {-->
<!--    margin-top: 30px;-->
<!--  }-->

<!--  .chart-title {-->
<!--    font-size: 18px;-->
<!--    font-weight: bold;-->
<!--    margin-bottom: 8px;-->
<!--  }-->

<!--  .chart-unit {-->
<!--    font-size: 12px;-->
<!--    color: #999;-->
<!--    margin-bottom: 15px;-->
<!--  }-->

<!--  .echarts-box {-->
<!--    margin: 0 auto;-->
<!--  }-->
<!--</style>-->



<template>
  <div class="device-dashboard">
    <!-- 顶部标题 -->
    <div class="dashboard-header">
      <h1 class="header-title">设备管理看板</h1>
      <div class="header-time">
        <span>{{ currentDate }}</span>
        <el-button type="text" @click="refreshAll">
          <i class="el-icon-refresh"></i> 刷新全部
        </el-button>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="dashboard-content">
      <!-- 左侧：设备地图 -->
      <div class="map-container">
        <div class="map-controls">
          <el-button type="primary" @click="refreshMap">
            <i class="el-icon-refresh-right"></i> 刷新地图
          </el-button>
          <el-button type="success" @click="addRandomDevice">
            <i class="el-icon-plus"></i> 添加设备
          </el-button>
          <el-input
            v-model="searchKeyword"
            placeholder="搜索设备名称或类型"
            @keyup.enter="filterDevices"
            class="search-input"
          >
            <template #prefix>
              <i class="el-icon-search"></i>
            </template>
          </el-input>
        </div>

        <div ref="mapChart" class="map-content"></div>

        <div class="map-legend">
          <div class="legend-item">
            <span class="legend-dot online"></span>
            <span class="legend-text">在线设备</span>
          </div>
          <div class="legend-item">
            <span class="legend-dot offline"></span>
            <span class="legend-text">离线设备</span>
          </div>
          <div class="legend-item">
            <span class="legend-dot fault"></span>
            <span class="legend-text">故障设备</span>
          </div>
        </div>
      </div>

      <!-- 右侧：统计信息 -->
      <div class="stats-container">
        <!-- 设备情况统计 -->
        <div class="stats-card">
          <div class="card-header">
            <h3 class="card-title">设备情况</h3>
          </div>
          <div class="stats-grid">
            <div class="stats-item usage-stats">
              <div class="stats-title">使用统计</div>
              <div class="stats-data">
                <div class="data-row">
                  <span class="data-label">全部设备</span>
                  <span class="data-value">{{ deviceStats.total }}</span>
                </div>
                <div class="data-row">
                  <span class="data-label">在用设备</span>
                  <span class="data-value">{{ deviceStats.inUse }}</span>
                </div>
                <div class="data-row">
                  <span class="data-label">闲置设备</span>
                  <span class="data-value">{{ deviceStats.idle }}</span>
                </div>
                <div class="data-row">
                  <span class="data-label">停用设备</span>
                  <span class="data-value">{{ deviceStats.disabled }}</span>
                </div>
              </div>
            </div>

            <div class="stats-item activation-stats">
              <div class="stats-title">激活情况（在用设备）</div>
              <div class="stats-data">
                <div class="data-row">
                  <span class="data-label">已激活设备</span>
                  <span class="data-value">{{ deviceStats.activated }}</span>
                </div>
                <div class="data-row">
                  <span class="data-label">未激活设备</span>
                  <span class="data-value">{{ deviceStats.unactivated }}</span>
                </div>
              </div>
            </div>

            <div class="stats-item status-stats">
              <div class="stats-title">运行状态（已激活设备）</div>
              <div class="stats-data">
                <div class="data-row">
                  <span class="data-label">正常设备</span>
                  <span class="data-value">{{ deviceStats.normal }}</span>
                </div>
                <div class="data-row">
                  <span class="data-label">故障设备</span>
                  <span class="data-value">{{ deviceStats.fault }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 待办事项 -->
        <div class="todo-card">
          <div class="card-header">
            <h3 class="card-title">待办事项</h3>
          </div>
          <div class="todo-grid">
            <div class="todo-item" v-for="(item, index) in todoItems" :key="index">
              <div class="todo-icon">
                <i :class="item.icon"></i>
              </div>
              <div class="todo-content">
                <div class="todo-label">{{ item.label }}</div>
                <div class="todo-count">{{ item.count }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 设备排行柱状图 -->
        <div class="chart-card">
          <div class="card-header">
            <h3 class="card-title">在用设备排行</h3>
            <div class="chart-unit">单位：台</div>
          </div>
          <div ref="barChart" class="chart-content"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted, onUnmounted, computed, watch } from 'vue';
  import * as echarts from 'echarts';
  import axios from 'axios';
  import { ElMessage } from 'element-plus';

  // 状态管理
  const mapChart = ref(null);
  const barChart = ref(null);
  let myChart = null;
  let barChartInstance = null;
  const errorMessage = ref('');
  const searchKeyword = ref('');
  const deviceList = ref([]);
  const currentDate = ref(new Date().toLocaleString());

  // 设备统计数据
  const deviceStats = ref({
    total: 276,
    inUse: 260,
    idle: 10,
    disabled: 6,
    activated: 212,
    unactivated: 48,
    normal: 208,
    fault: 4
  });

  // 待办事项数据
  const todoItems = ref([
    { label: '待激活', count: 2, icon: 'el-icon-clock-in' },
    { label: '待安装', count: 0, icon: 'el-icon-s-tools' },
    { label: '型号补充', count: 0, icon: 'el-icon-document-add' },
    { label: '安装地点补充', count: 1, icon: 'el-icon-map-location' }
  ]);

  // 柱状图数据
  const barData = ref({
    xAxis: ['光刻机', '刻蚀机', '薄膜沉积设备', '离子注入机', '机械抛光', '清洗机', '氧化炉', '晶圆切割机', '晶元建博机', '测试机'],
    yAxis: [84, 79, 60, 45, 40, 21, 18, 15, 11, 8]
  });

  // 生命周期钩子
  onMounted(async () => {
    try {
      // 初始化地图
      const response = await axios.get('/china.json');
      echarts.registerMap('china', response.data);

      myChart = echarts.init(mapChart.value);
      myChart.showLoading();

      setTimeout(() => {
        deviceList.value = generateRandomDevices(50);
        renderMap();
        myChart.hideLoading();
      }, 800);

      // 初始化柱状图
      barChartInstance = echarts.init(barChart.value);
      renderBarChart();

      // 监听窗口大小变化
      window.addEventListener('resize', handleResize);

      // 每5分钟刷新时间
      const interval = setInterval(() => {
        currentDate.value = new Date().toLocaleString();
      }, 300000);
    } catch (error) {
      console.error('初始化失败:', error);
      errorMessage.value = `初始化失败: ${error.message}`;
    }
  });

  onUnmounted(() => {
    // 销毁图表实例
    if (myChart) {
      myChart.dispose();
    }
    if (barChartInstance) {
      barChartInstance.dispose();
    }

    // 移除事件监听器
    window.removeEventListener('resize', handleResize);
  });

  // 工具函数
  const generateRandomDevices = (count = 10) => {
    const cities = [
      { name: '北京', lng: 116.407526, lat: 39.90403 },
      { name: '上海', lng: 121.473701, lat: 31.230416 },
      { name: '广州', lng: 113.264435, lat: 23.12911 },
      { name: '深圳', lng: 114.057868, lat: 22.543099 },
      { name: '成都', lng: 104.065735, lat: 30.572269 },
      { name: '杭州', lng: 120.15358, lat: 30.287458 },
      { name: '南京', lng: 118.767413, lat: 32.041544 },
      { name: '武汉', lng: 114.298572, lat: 30.584355 },
      { name: '重庆', lng: 106.504959, lat: 29.533155 },
      { name: '西安', lng: 108.948021, lat: 34.263161 },
      { name: '哈尔滨', lng: 126.642464, lat: 45.756966 },
      { name: '长春', lng: 125.323449, lat: 43.886841 },
      { name: '沈阳', lng: 123.429092, lat: 41.807558 },
      { name: '济南', lng: 117.000923, lat: 36.675808 },
      { name: '郑州', lng: 113.625366, lat: 34.747298 },
      { name: '合肥', lng: 117.285659, lat: 31.861194 },
      { name: '福州', lng: 119.295992, lat: 26.082715 },
      { name: '南昌', lng: 115.892151, lat: 28.676493 },
      { name: '长沙', lng: 112.983454, lat: 28.112766 },
      { name: '贵阳', lng: 106.713478, lat: 26.577873 },
      { name: '昆明', lng: 102.71225, lat: 25.040609 },
      { name: '南宁', lng: 108.320004, lat: 22.82402 },
      { name: '海口', lng: 110.33119, lat: 20.031971 },
      { name: '兰州', lng: 103.823557, lat: 36.058039 },
      { name: '西宁', lng: 101.778916, lat: 36.623178 },
      { name: '银川', lng: 106.23248, lat: 38.48644 },
      { name: '乌鲁木齐', lng: 87.617733, lat: 43.826635 },
      { name: '拉萨', lng: 91.114503, lat: 29.650007 }
    ];

    return Array.from({ length: count }, (_, i) => {
      const city = cities[Math.floor(Math.random() * cities.length)];
      const lngOffset = (Math.random() - 0.5) * 1.5;
      const latOffset = (Math.random() - 0.5) * 1.5;

      const status = ['在线', '离线', '故障'][Math.floor(Math.random() * 3)];
      const type = ['服务器', '传感器', '摄像头', '路由器', '交换机', '控制器'][Math.floor(Math.random() * 6)];

      return {
        id: `device-${Date.now()}-${i}`,
        name: `${type}${i + 1}`,
        type,
        status,
        lng: city.lng + lngOffset,
        lat: city.lat + latOffset,
        temperature: status === '故障' ? Math.floor(Math.random() * 10) + 70 : Math.floor(Math.random() * 30) + 20,
        load: status === '故障' ? 100 : Math.floor(Math.random() * 80) + 10,
        lastSeen: new Date().toISOString()
      };
    });
  };

  // 地图相关函数
  const renderMap = () => {
    try {
      // 构建地图数据
      const lineData = deviceList.value.map(device => ({
        coords: [[device.lng, device.lat], [device.lng, device.lat + 3]],
        status: device.status,
        deviceInfo: device
      }));

      const scatterData = deviceList.value.map(device => ({
        value: [device.lng, device.lat + 0],
        status: device.status,
        deviceInfo: device
      }));

      // 计算设备状态统计
      const statusCounts = deviceList.value.reduce((acc, device) => {
        acc[device.status] = (acc[device.status] || 0) + 1;
        return acc;
      }, { '在线': 0, '离线': 0, '故障': 0 });

      // 配置项
      const option = {
        backgroundColor: 'rgba(15, 23, 42, 0.95)',
        title: {
          text: `全国设备分布 (${deviceList.value.length}台)`,
          left: 'center',
          textStyle: {
            color: '#e2e8f0',
            fontSize: 18,
            fontWeight: 500
          }
        },
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(15, 23, 42, 0.9)',
          borderColor: 'rgba(54, 207, 251, 0.6)',
          borderWidth: 1,
          textStyle: {
            color: '#E2E8F0',
            fontSize: 13
          },
          formatter: (params) => {
            const device = params.data.deviceInfo;
            const lastSeen = new Date(device.lastSeen).toLocaleString();

            return `
            <div style="font-weight:bold; color:#36CFFB">${device.name}</div>
            <div class="tooltip-row"><span class="tooltip-label">类型:</span> ${device.type}</div>
            <div class="tooltip-row"><span class="tooltip-label">状态:</span> <span style="color:${getDeviceColor(device.status)}">${getStatusText(device.status)}</span></div>
            <div class="tooltip-row"><span class="tooltip-label">位置:</span> ${device.lng.toFixed(2)}, ${device.lat.toFixed(2)}</div>
            <div class="tooltip-row"><span class="tooltip-label">温度:</span> ${device.temperature}°C</div>
            <div class="tooltip-row"><span class="tooltip-label">负载:</span> ${device.load}%</div>
            <div class="tooltip-row"><span class="tooltip-label">最后在线:</span> ${lastSeen}</div>
          `;
          }
        },
        geo: {
          map: 'china',
          roam: true,
          zoom: 1.2,
          label: {
            show: true,
            color: '#94a3b8',
            fontSize: 10,
            formatter: (params) => {
              // 避免南海诸岛显示文字
              if (params.name === '南海诸岛') return '';
              return params.name;
            }
          },
          itemStyle: {
            areaColor: 'rgba(30, 41, 59, 0.8)',
            borderColor: 'rgba(54, 207, 251, 0.3)',
            borderWidth: 0.8
          },
          emphasis: {
            itemStyle: {
              areaColor: 'rgba(54, 207, 251, 0.15)'
            }
          }
        },
        series: [
          {
            name: '设备光柱',
            type: 'lines',
            coordinateSystem: 'geo',
            data: lineData,
            effect: {
              show: true,
              period: 4,
              trailLength: 0.4,
              color: '#36CFFB',
              symbolSize: 6
            },
            lineStyle: {
              color: (params) => getDeviceColor(params.data.status),
              width: 2,
              opacity: 0.8,
              curveness: 0
            }
          },
          {
            name: '光柱顶端',
            type: 'scatter',
            coordinateSystem: 'geo',
            data: scatterData,
            symbolSize: 8,
            itemStyle: {
              color: (params) => getDeviceColor(params.data.status),
              shadowBlur: 10,
              shadowColor: (params) => getDeviceColor(params.data.status),
              opacity: 0.8
            },
            label: {
              show: false
            }
          }
        ]
      };

      myChart.setOption(option);
    } catch (error) {
      console.error('渲染地图失败:', error);
      errorMessage.value = `地图渲染失败: ${error.message}`;
    }
  };

  // 柱状图相关函数
  const renderBarChart = () => {
    try {
      const option = {
        backgroundColor: 'rgba(15, 23, 42, 0.95)',
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
            shadowStyle: {
              color: 'rgba(54, 207, 251, 0.1)'
            }
          },
          backgroundColor: 'rgba(15, 23, 42, 0.9)',
          textStyle: {
            color: '#E2E8F0'
          }
        },
        xAxis: {
          type: 'category',
          data: barData.value.xAxis,
          axisLabel: {
            color: '#94A3B8',
            fontSize: 12,
            interval: 0,
            rotate: 45
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(54, 207, 251, 0.3)'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: '数量（台）',
          nameTextStyle: {
            color: '#94A3B8',
            fontSize: 13
          },
          axisLabel: {
            color: '#94A3B8',
            fontSize: 12
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(54, 207, 251, 0.3)'
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(54, 207, 251, 0.1)'
            }
          }
        },
        series: [
          {
            name: '在用设备数量',
            type: 'bar',
            data: barData.value.yAxis,
            barWidth: '40%',
            itemStyle: {
              color: '#36CFFB',
              borderRadius: [6, 6, 0, 0],
              shadowBlur: 10,
              shadowColor: 'rgba(54, 207, 251, 0.3)'
            },
            label: {
              show: true,
              position: 'top',
              color: '#E2E8F0',
              fontSize: 12
            }
          }
        ],
        grid: {
          left: '5%',
          right: '5%',
          bottom: '15%',
          top: '10%',
          containLabel: true
        }
      };

      barChartInstance.setOption(option);
    } catch (error) {
      console.error('渲染柱状图失败:', error);
      errorMessage.value = `柱状图渲染失败: ${error.message}`;
    }
  };

  // 辅助函数
  const getDeviceColor = (status) => {
    switch (status) {
      case '在线': return '#22c55e'; // 绿色
      case '离线': return '#64748b'; // 灰色
      case '故障': return '#ef4444'; // 红色
      default: return '#3b82f6'; // 蓝色
    }
  };

  const getStatusText = (status) => {
    const statusMap = { online: '在线', offline: '离线', fault: '故障' };
    return statusMap[status] || status;
  };

  const handleResize = () => {
    myChart && myChart.resize();
    barChartInstance && barChartInstance.resize();
  };

  const handleMapResize = () => {
    myChart && myChart.resize();
  };

  const handleBarResize = () => {
    barChartInstance && barChartInstance.resize();
  };

  // 交互函数
  const refreshMap = () => {
    myChart.showLoading();
    setTimeout(() => {
      deviceList.value = generateRandomDevices(50);
      renderMap();
      myChart.hideLoading();
      ElMessage.success('地图数据已刷新');
    }, 800);
  };

  const addRandomDevice = () => {
    const newDevice = generateRandomDevices(1)[0];
    deviceList.value = [...deviceList.value, newDevice];
    renderMap();
    ElMessage.info(`已添加新设备: ${newDevice.name}`);
  };

  const filterDevices = () => {
    if (!searchKeyword.value.trim()) {
      renderMap();
      return;
    }

    const keyword = searchKeyword.value.toLowerCase();
    const filtered = deviceList.value.filter(device =>
      device.name.toLowerCase().includes(keyword) ||
      device.type.toLowerCase().includes(keyword)
    );

    if (myChart) {
      const lineData = filtered.map(device => ({
        coords: [[device.lng, device.lat], [device.lng, device.lat + 3]],
        status: device.status,
        deviceInfo: device
      }));

      const scatterData = filtered.map(device => ({
        value: [device.lng, device.lat + 0],
        status: device.status,
        deviceInfo: device
      }));

      myChart.setOption({
        series: [
          {
            name: '设备光柱',
            data: lineData
          },
          {
            name: '光柱顶端',
            data: scatterData
          }
        ]
      });

      ElMessage.info(`找到 ${filtered.length} 个匹配结果`);
    }
  };

  const refreshAll = () => {
    // 同时刷新地图和统计数据
    refreshMap();

    // 模拟刷新统计数据
    setTimeout(() => {
      // 随机调整统计数据
      deviceStats.value = {
        ...deviceStats.value,
        total: deviceStats.value.total + Math.floor(Math.random() * 10) - 5,
        inUse: deviceStats.value.inUse + Math.floor(Math.random() * 8) - 4,
        idle: deviceStats.value.idle + Math.floor(Math.random() * 3) - 1,
        disabled: deviceStats.value.disabled + Math.floor(Math.random() * 2) - 1,
        activated: deviceStats.value.activated + Math.floor(Math.random() * 6) - 3,
        unactivated: deviceStats.value.unactivated + Math.floor(Math.random() * 4) - 2,
        normal: deviceStats.value.normal + Math.floor(Math.random() * 5) - 2,
        fault: deviceStats.value.fault + Math.floor(Math.random() * 2) - 1
      };

      // 随机调整柱状图数据
      barData.value.yAxis = barData.value.yAxis.map(value =>
        value + Math.floor(Math.random() * 10) - 5
      );

      // 重新渲染柱状图
      renderBarChart();

      ElMessage.success('全部数据已刷新');
    }, 1000);
  };
</script>

<style scoped>
  .device-dashboard {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background: linear-gradient(135deg, #0F172A 0%, #1E293B 100%);
    padding: 20px;
    font-family: 'Inter', system-ui, sans-serif;
    color: #E2E8F0;
  }

  .dashboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .header-title {
    font-size: 28px;
    font-weight: 600;
    color: #FFFFFF;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }

  .header-time {
    display: flex;
    align-items: center;
    gap: 16px;
    color: #94A3B8;
    font-size: 14px;
  }

  .dashboard-content {
    flex: 1;
    display: flex;
    gap: 20px;
  }

  /* 左侧地图部分 */
  .map-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: rgba(15, 23, 42, 0.7);
    border-radius: 16px;
    backdrop-filter: blur(8px);
    border: 1px solid rgba(54, 207, 251, 0.1);
    overflow: hidden;
    position: relative;
  }

  .map-controls {
    display: flex;
    gap: 12px;
    padding: 16px;
    z-index: 10;
  }

  .search-input {
    width: 240px;
  }

  .map-content {
    flex: 1;
    width: 100%;
    position: relative;
  }

  .map-legend {
    position: absolute;
    bottom: 16px;
    right: 16px;
    display: flex;
    gap: 20px;
    background: rgba(15, 23, 42, 0.8);
    padding: 10px 16px;
    border-radius: 8px;
    backdrop-filter: blur(4px);
    border: 1px solid rgba(54, 207, 251, 0.2);
    z-index: 10;
  }

  .legend-item {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .legend-dot {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    display: inline-block;
  }

  .legend-dot.online { background-color: #22c55e; }
  .legend-dot.offline { background-color: #64748b; }
  .legend-dot.fault { background-color: #ef4444; }

  .legend-text {
    color: #E2E8F0;
    font-size: 12px;
  }

  /* 右侧统计部分 */
  .stats-container {
    width: 40%;
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .stats-card, .todo-card, .chart-card {
    background: rgba(15, 23, 42, 0.7);
    border-radius: 16px;
    backdrop-filter: blur(8px);
    border: 1px solid rgba(54, 207, 251, 0.1);
    overflow: hidden;
  }

  .card-header {
    padding: 16px;
    border-bottom: 1px solid rgba(54, 207, 251, 0.1);
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-title {
    font-size: 18px;
    font-weight: 500;
    color: #FFFFFF;
  }

  .chart-unit {
    font-size: 12px;
    color: #94A3B8;
  }

  /* 设备情况统计 */
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    padding: 16px;
  }

  .stats-item {
    padding: 16px;
    border-radius: 12px;
  }

  .usage-stats {
    background: rgba(59, 130, 246, 0.1);
    border: 1px solid rgba(59, 130, 246, 0.2);
  }

  .activation-stats {
    background: rgba(249, 115, 22, 0.1);
    border: 1px solid rgba(249, 115, 22, 0.2);
  }

  .status-stats {
    background: rgba(239, 68, 68, 0.1);
    border: 1px solid rgba(239, 68, 68, 0.2);
  }

  .stats-title {
    font-size: 14px;
    font-weight: 500;
    color: #FFFFFF;
    margin-bottom: 12px;
  }

  .stats-data {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .data-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .data-label {
    font-size: 12px;
    color: #94A3B8;
  }

  .data-value {
    font-size: 14px;
    font-weight: 500;
    color: #FFFFFF;
  }

  /* 待办事项 */
  .todo-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
    padding: 16px;
  }

  .todo-item {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 16px;
    background: rgba(30, 41, 59, 0.5);
    border-radius: 12px;
    transition: all 0.3s ease;
  }

  .todo-item:hover {
    background: rgba(30, 41, 59, 0.8);
    transform: translateY(-2px);
  }

  .todo-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba(54, 207, 251, 0.1);
    color: #36CFFB;
    font-size: 18px;
  }

  .todo-content {
    flex: 1;
  }

  .todo-label {
    font-size: 14px;
    color: #94A3B8;
  }

  .todo-count {
    font-size: 20px;
    font-weight: 600;
    color: #FFFFFF;
  }

  /* 柱状图 */
  .chart-content {
    width: 100%;
    height: 300px;
    padding: 16px;
  }

  /* 自定义tooltip样式 */
  .tooltip-row {
    margin: 4px 0;
    display: flex;
    align-items: center;
  }

  .tooltip-label {
    color: #94A3B8;
    margin-right: 8px;
    min-width: 60px;
    display: inline-block;
  }
</style>


